package com.jsmile.cloud.authc.sys.controller;

import java.util.Map;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.google.common.collect.Maps;
import com.jsmile.cloud.authc.api.req.ReqSysUserLogin;
import com.jsmile.cloud.authc.api.req.ReqToken;
import com.jsmile.mail.security.controller.AuthcController;
import com.jsmile.mail.security.handler.JsmileContext;
import com.jsmile.mail.security.kit.LoginKit;
import com.jsmile.mail.security.security.SecurityKit;
import com.jsmile.mall.api.JSmileResult;
import com.jsmile.mall.api.annotation.CurrentContext;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author 龚亮
 * @version 1.0
 * @desc 控制器
 * @date 2018年08月25日 04:57:24
 */
@RestController
@Api(tags = "统一用户登录")
@Slf4j
@AllArgsConstructor
public class SysLoginController extends AuthcController {

    private final RestTemplate restTemplate;

    @RequestMapping(value = "/sso/login")
    @ApiOperation(value = "统一用户登录")
    public JSmileResult mobileLogin(@RequestBody ReqSysUserLogin sysUserLoginTo, @CurrentContext JsmileContext jsmileContext) {
        JSmileResult result = JSmileResult.success();
        sysUserLoginTo.setTenantId(jsmileContext.getTenantId());
        Map map = LoginKit.login(restTemplate, sysUserLoginTo);
        result.setResData(map);
        return result;
    }

    @RequestMapping(value = "/sso/refresh/token")
    @ApiOperation(value = "统一刷新token")
    public JSmileResult refreshToken(@RequestBody ReqToken tokenTo, @CurrentContext JsmileContext jsmileContext) {
        JSmileResult result = JSmileResult.success();
        Map map = LoginKit.refreshToken(restTemplate, tokenTo.getToken(), jsmileContext.getUserType(), jsmileContext.getTenantId());
        result.setResData(map);
        return result;
    }

    /**
     * 获取用户所拥有的菜单
     */
    @ApiOperation(value = "获取用户所拥有的菜单", notes = "获取用户所拥有的菜单")
    @RequestMapping(value = "/sys/getMenu", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiIgnore
    public JSmileResult getMenu(@RequestBody Map<String, Object> req) {
        JSmileResult result = JSmileResult.success();
        Map<String, Object> res = Maps.newHashMap();
        res.put("menus", SecurityKit.getUser().getMenu());
        res.put("realName", SecurityKit.getSysUser().getRealName());
        result.setResData(res);
        return result;
    }
}
